package com.example.sign;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.itextpdf.awt.geom.Rectangle2D.Float;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.springframework.util.StringUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;


import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PDFUtils {
    // 定义关键字
    private static String KEY_WORD = "承诺人";


    /**
     * @param srcFile    源pdf 位置
     * @param destFile   生成pdf 位置
     * @param text       水印文字
     * @param imgPath    水印图片位置
     * @param textWidth  起始位置 x轴
     * @param textHeight 起始位置 Y 轴
     * @param page       第几页插入
     * @throws Exception
     */
    public static void addImgWaterMark(String srcFile, String destFile, String text, String imgPath,
                                       int textWidth, int textHeight, int page) throws Exception {
        addImgWaterMark(new FileInputStream(srcFile), new FileOutputStream(destFile), text, new FileInputStream(imgPath), textWidth, textHeight, page);
    }

    /**
     * @param inputStream    源pdf输入流
     * @param outputStream   生成pdf输入流
     * @param text           水印文字
     * @param imgInputStream 水印图片流
     * @param textWidth      起始位置 x轴
     * @param textHeight     起始位置 Y 轴
     * @param page           第几页插入
     * @throws Exception
     */
    public static void addImgWaterMark(InputStream inputStream, OutputStream outputStream, String text, InputStream imgInputStream,
                                       int textWidth, int textHeight, int page) throws Exception {
        // 待加水印的文件
        PdfReader reader = new PdfReader(inputStream);
        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        // 循环对每页插入水印
        for (int i = 1; i < total; i++) {
            if (page != i) {
                continue;
            }
            content = stamper.getOverContent(i);
            content.saveState();
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(1f);
            content.setGState(gs);
            content.restoreState();
            content.beginText();

            if (imgInputStream != null) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] b = new byte[2048];
                int len = -1;
                while ((len = imgInputStream.read(b)) != -1) {
                    bos.write(b, 0, len);
                }
                imgInputStream.close();
                bos.close();
                Image image = Image.getInstance(bos.toByteArray());
                // 设置坐标 绝对位置 X Y
                image.setAbsolutePosition(textWidth + 40, textHeight - 60);
                // 设置旋转弧度
                image.setRotation(0);// 旋转 弧度
                // 设置旋转角度
                image.setRotationDegrees(0);// 旋转 角度
                // 设置等比缩放

                image.scalePercent((int)(10.0 / (image.getAbsoluteX() /980.0 ) ));// 依照比例缩放
                content.addImage(image);
            }
            if (text != null && !"".equals(text)) {

                // // 设置字体

                BaseFont font = BaseFont.createFont("msyh.ttf", BaseFont.IDENTITY_H,
                        BaseFont.EMBEDDED);
                // 开始写入水印
                content.setFontAndSize(font, 12);
                content.setTextMatrix(15, 15);
                content.setColorFill(BaseColor.BLACK);
                content.showTextAligned(Element.ALIGN_LEFT, text, textWidth,
                        textHeight - 60, 0);
            }
            // 开始
            content.endText();

        }
        stamper.close();

    }

    /**
     * 返回关键字所在的坐标和页数 float[0] >> X float[1] >> Y float[2] >> page
     */
    public static float[] getKeyWords(byte[] pdfIn) {
        try {
            PdfReader pdfReader = new PdfReader(pdfIn);
            float[] keyWords = getKeyWords(pdfReader);
            return keyWords;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static float[] getKeyWords(String path) {
        try {
            PdfReader pdfReader = new PdfReader(path);
            float[] keyWords = getKeyWords(pdfReader);
            return keyWords;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static float[] getKeyWords(PdfReader pdfReader) {
        final float[][] resu = {null};
        try {
            // 定义返回值
            int pageNum = pdfReader.getNumberOfPages();
            PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(
                    pdfReader);
            // 下标从1开始
            for (int i = 1; i <= pageNum; i++) {
                int finalI = i;
                pdfReaderContentParser.processContent(i, new RenderListener() {
                    @Override
                    public void renderText(TextRenderInfo textRenderInfo) {
                        String text = textRenderInfo.getText();
                        if (null != text && text.contains(KEY_WORD)) {
                            Float boundingRectange = textRenderInfo.getBaseline().getBoundingRectange();
                            resu[0] = new float[3];
                            resu[0][0] = boundingRectange.x;
                            resu[0][1] = boundingRectange.y;
                            resu[0][2] = finalI;
                        }
                    }

                    @Override
                    public void renderImage(ImageRenderInfo arg0) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void endTextBlock() {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void beginTextBlock() {
                        // TODO Auto-generated method stub

                    }
                });
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resu[0];
    }

    /**
     * 将html  转换为 PDF
     * @param args
     * @throws Exception
     */

    /**
     * 生成 PDF 文件
     *
     * @param out  输出流
     * @param html HTML字符串
     * @throws IOException       IO异常
     * @throws DocumentException Document异常
     */
    public static void createPDF(OutputStream out, String html) throws IOException, DocumentException, com.lowagie.text.DocumentException {
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, out);
        document.open();
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(html.getBytes()), Charset.forName("UTF-8"), new AsianFontProvider());
        document.close();


    }

    public static void createPDF(OutputStream out, byte[] html) throws IOException, DocumentException, com.lowagie.text.DocumentException {
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, out);
        document.open();
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        
        worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(html), Charset.forName("UTF-8"), new AsianFontProvider());
        document.close();


    }

    /**
     * 用于中文显示的Provider
     */
    static class AsianFontProvider extends XMLWorkerFontProvider {
        @Override
        public Font getFont(final String fontname, String encoding, float size, final int style) {
            try {
                BaseFont font = BaseFont.createFont("msyh.ttf", BaseFont.IDENTITY_H,
                        BaseFont.EMBEDDED);
                return new Font(font, size, Font.BOLD);
            } catch (Exception e) {
            }
            return super.getFont(fontname, encoding, size, style);
        }
    }

    public static void main(String[] args) throws Exception {
        // // 将html  转换为 PDF
        long time = new Date().getTime();
        String path = "D:\\xinda\\sign\\src\\main\\java\\com\\example\\sign\\test.txt";
        try (FileInputStream fis = new FileInputStream(path);
             InputStreamReader isr = new InputStreamReader(fis);
             BufferedReader br = new BufferedReader(isr)) {

            StringBuilder sb = new StringBuilder();
            String s = "";
            while ((s = br.readLine()) != null) {
                //每次读取一行
                sb.append(s);
            }
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            createPDF(outputStream, sb.toString());

            float[] keyWords = getKeyWords(outputStream.toByteArray());
            System.out.println(" getKeyWords " + keyWords[0]);
            System.out.println(" getKeyWords " + keyWords[1]);
            System.out.println(" getKeyWords " + keyWords[2]);

            addImgWaterMark(new ByteArrayInputStream(outputStream.toByteArray()),
                    new FileOutputStream("D:\\Users\\Administrator\\Desktop\\asdfasdf4.pdf"),
                    new SimpleDateFormat("yyyy 年 MM 月 dd 日").format(new Date()),
                    new FileInputStream("D:\\Users\\Administrator\\Desktop\\b57d51a77925edd64b21cc668f5b29e.png"),
                    (int) (keyWords[0]), (int) (keyWords[1]), (int) keyWords[2]);

        }

        System.out.println("生成时间花费 ：" + (new Date().getTime() - time));
        // float[] keyWords = getKeyWords("D:\\Users\\Administrator\\Desktop\\asdfasdf4.pdf");
        // System.out.println(" getKeyWords " + keyWords[0]);
        // System.out.println(" getKeyWords " + keyWords[1]);
        // System.out.println(" getKeyWords " + keyWords[2]);
        // addImgWaterMark("D:\\Users\\Administrator\\Desktop\\asdfasdf4.pdf", "D:\\Users\\Administrator\\Desktop\\asdfasdf6.pdf", new SimpleDateFormat("yyyy 年 MM 月 dd 日").format(new Date()), "D:\\Users\\Administrator\\Desktop\\b57d51a77925edd64b21cc668f5b29e.png", (int) (keyWords[0]), (int) (keyWords[1]), (int) keyWords[2]);


    }
}
